package com.yb.guigu.pick.security.generator;

import com.yb.guigu.pick.core.constant.LoginTypeEnum;
import com.yb.guigu.pick.core.exception.GuiguBusinessException;
import com.yb.guigu.pick.cache.manager.api.GuiguPickStringCacheManager;
import com.yb.guigu.pick.security.bean.GuiguPickUser;
import com.yb.guigu.pick.core.constant.RedisKeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
public class GuiguPickLoginCodeGenerator implements GuiguPickCodeGenerator {

    GuiguPickStringCacheManager guiguPickStringCacheManager;

    public GuiguPickLoginCodeGenerator(GuiguPickStringCacheManager guiguPickStringCacheManager){
        this.guiguPickStringCacheManager=guiguPickStringCacheManager;
    }
    @Override
    public String generate(GuiguPickUser guiguPickUser) {

        String username = guiguPickUser.getUsername();

        if(!StringUtils.hasText(username)){
            log.info("GuiguPickLoginCodeGenerator generate username is empty",username);
            throw new GuiguBusinessException("用户名username不能为空");
        }

        String code = UUID.randomUUID().toString().replaceAll("-", "");

        log.info("GuiguPickLoginCodeGenerator generate for {} code {}",username,code);

        guiguPickStringCacheManager.expire(String.format(RedisKeyConstant.LOGIN_USER_LOGINCODE_KEY,username),code,60, TimeUnit.SECONDS);

        return code;
    }

    @Override
    public boolean support(String loginType) {
        return LoginTypeEnum.LOGIN_CODE.getLoginType().equals(loginType);
    }
}
